<?php

namespace App\Console\Commands;

use App\Admin\Tools\ComWechatRobot;
use App\Models\MemberTask;
use App\Models\TaskMemberMap;
use App\Models\TeamMember;
use Illuminate\Console\Command;

class TaskStatusWatch extends Command
{
    const PER_PAGE_LIMIT = 50;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'task:watch';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新任务进展状态值';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $page_num = 1;
        while($act_list = MemberTask::where('status', MemberTask::TASK_STATUS_ING)
            ->where('progress', MemberTask::TASK_PROGRESS_NORMAL)
            ->paginate(self::PER_PAGE_LIMIT, ['*'], 'page', $page_num)){
            if ($act_list){
                $act_list = $act_list->toArray();
                if ($page_num > $act_list['last_page']){
                    return $this->line('complete!');
                }
                $be_chg_task_id_list = [];
                foreach ($act_list['data'] as $key => $value){
                    if (strtotime($value['end_time']) < time()){
                        $be_chg_task_id_list[] = $value['task_id'];
                        $member_id_list = TaskMemberMap::where('task_id', $value['task_id'])->get();
                        if ($member_id_list){
                            $member_str = '';
                            $member_list = TeamMember::whereIn('member_id', $member_id_list->pluck('member_id')->toArray())->get();
                            foreach ($member_list as $member){
                                $member_str .= "@{$member['member_name']} ";
                            }
                            app(ComWechatRobot::class)->sentTextMsg("{$member_str} 任务延期通知：\n项目名称：{$value['project_name']}\n任务名称：{$value['task_name']}\n已延期，请尽快处理！");
                        }
                    }
                }
                if (!empty($be_chg_task_id_list)){
                    if (false === MemberTask::whereIn('task_id', $be_chg_task_id_list)->update(['progress' => MemberTask::TASK_PROGRESS_DELAY])){
                        return $this->error('任务进展状态更新失败');
                    }
                }
                $page_num++;
            }
        }
        return $this->line('更新任务进展状态值:COMPLETE!');
    }
}
